<template>
  <div class="mod-user">
    <div class="mod-user">
      <el-form :model="query" :inline="true" @keyup.enter.native="getSubjectList()">
        <el-form-item>
          <el-select
            @change="changeSchoolTypeForQuery"
            v-model="query.school_type"
            filterable
            clearable
            placeholder="请选择所属阶段">
            <el-option
              v-for="item in schoolTypeList"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="query.grade_type"
            filterable
            clearable
            placeholder="请选择年级">
            <el-option
              v-for="item in gradeTypeList"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button v-if="hasPermission(['system:course:list'])" type="success" icon="el-icon-search" @click="searchCourse()">查询</el-button>
          <el-button v-if="hasPermission(['system:course:update'])" type="primary" @click="addCourse">新增</el-button>
          <el-button v-if="hasPermission(['system:course:batchDelete'])" @click="batchDelete" type="danger">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="courseList"
        border
        v-loading="loading"
        style="width: 100%;">

        <!--<el-table-column-->
          <!--type="selection"-->
          <!--header-align="center"-->
          <!--align="center"-->
          <!--width="50">-->
        <!--</el-table-column>-->

        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          label="课程名称">
        </el-table-column>

        <el-table-column
          prop="head_img"
          align="center"
          label="课程封面">
          <template slot-scope="scope">
            <img v-if="scope.row.head_img" style="width: 40px; height: 40px;" :src="fileUrl + scope.row.head_img"/>
          </template>
        </el-table-column>

        <el-table-column
          prop="grade_type"
          header-align="center"
          align="center"
          label="所属年级">
          <template slot-scope="scope">
            <el-tag size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="subject_name"
          header-align="center"
          align="center"
          label="所属科目">
        </el-table-column>

        <el-table-column
          prop="status"
          header-align="center"
          align="center"
          label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 2" type="success" effect="dark">已上架</el-tag>
            <el-tag v-if="scope.row.status === 1" type="warning" effect="dark">草稿</el-tag>
            <el-tag v-if="scope.row.status === 0" type="danger" effect="dark">已下架</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="create_date"
          header-align="center"
          align="center"
          width="180"
          :formatter="formatterCreateDate"
          label="创建时间">
        </el-table-column>

        <el-table-column
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link">
                操作<i class="el-icon-caret-bottom"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item icon="el-icon-tickets" @click.native="relevanceCourseQuestion(scope.row)">试题管理</el-dropdown-item>
                <el-dropdown-item
                  @click.native="undercarriageCourse(scope.row,2)"
                  v-if="scope.row.status === 1"
                  icon="el-icon-upload2">上架</el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 2"
                  @click.native="undercarriageCourse(scope.row, 1)"
                  icon="el-icon-download">下架</el-dropdown-item>
                <el-dropdown-item
                  @click.native="updateCourse(scope.row)"
                  v-if="hasPermission(['system:course:update'])"
                  icon="el-icon-edit">修改</el-dropdown-item>
                <el-dropdown-item
                  @click.native="deleteCourseById(scope.row)"
                  v-if="hasPermission(['system:course:deleteById'])"
                  icon="el-icon-delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 试题列表 -->
      <course-question-dialog-list
        :gradeTypeList="gradeTypeList"
        :showFlag="questionListDialog"
        @closeCourseQuestionDialog="closeCourseQuestionDialog"
        :params="queryParams">
      </course-question-dialog-list>

      <el-pagination
        background
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <el-dialog
        :title="!form.id ? '新增课程' : '修改课程'"
        :close-on-click-modal="false"
        :visible.sync="showFlag">
            <el-form :model="form" :rules="rules" ref="form" @keyup.enter.native="saveOrUpdate()" label-width="80px">
              <el-form-item label="课程名称" prop="name">
                <el-input v-model="form.name" placeholder="课程名称"></el-input>
              </el-form-item>

              <el-form-item label="课程封面" prop="head_img">
                <div v-if="form.head_img">
                  <ul class="el-upload-list el-upload-list--picture-card"
                      style="display: inline-block;">
                    <li class="el-upload-list__item is-success">
                      <img :src="fileUrl + form.head_img" alt=""
                           class="el-upload-list__item-thumbnail">
                      <a class="el-upload-list__item-name"><i class="el-icon-document"></i></a>
                      <label class="el-upload-list__item-status-label">
                        <i class="el-icon-upload-success el-icon-check"></i></label> <i
                      class="el-icon-close"></i>
                      <i class="el-icon-close-tip">按 delete 键可删除</i>
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview"  @click="lookHeadImg"><i
                          class="el-icon-zoom-in"></i></span>
                          <span class="el-upload-list__item-delete" @click="deleteHeadImg"><i
                            class="el-icon-delete"></i></span>
                        </span>
                      <el-dialog
                        :visible.sync="headImageVisible"
                        custom-class="image-dialog"
                        append-to-body>
                        <img width="100%" :src="fileUrl + form.head_img" alt="">
                      </el-dialog>
                    </li>
                  </ul>
                </div>
                <div v-else>
                  <el-upload
                    :action="uploadAction"
                    :headers="headers"
                    :with-credentials="true"
                    class="avatar-uploader"
                    :on-success="uploadHeadImgSuccess"
                    :before-upload="beforeUploadHeadImg"
                    :show-file-list="false">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
              </el-form-item>

            <el-form-item label="所属阶段" placeholder="所属阶段" prop="school_type">
              <el-select
                @change="changeSchoolType"
                v-model="form.school_type"
                filterable
                clearable
                placeholder="请选择">
                <el-option
                  v-for="item in schoolTypeList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>

          <el-form-item label="所属年级" placeholder="所属年级" prop="grade_type">
            <el-select
              @change="changeGradeType"
              v-model="form.grade_type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in changeGradeTypeList"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="所属科目" placeholder="所属科目" prop="subject_id">
            <el-select
              v-model="form.subject_id"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in changeSubjectList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="课程简介">
            <el-input type="textarea" v-model="form.represent" placeholder="请输入课程简介"></el-input>
          </el-form-item>

          <el-form-item label="首页推荐">
            <el-radio-group v-model="form.recommend_index_flag">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="排序">
            <el-input v-model="form.sort" placeholder="排序(数字越大,排名越靠前)"></el-input>
          </el-form-item>
        </el-form>
       <span slot="footer"  class="dialog-footer">
          <el-button @click="showFlag = false" size="small">取消</el-button>
          <el-button type="warning" v-if="form.status !== 2" size="small" @click="saveOrUpdateCourse(1)">保存草稿</el-button>
          <el-button type="primary" size="small" @click="saveOrUpdateCourse(2)">保存并发布</el-button>
       </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  /* eslint-disable no-unused-vars,no-trailing-spaces,no-redeclare */
  import courseQuestionDialogList from '@/components/education/course-question-dialog-list'
  import { getSchoolTypeListApi, getGradeTypeListApi, getDictValueListByParentId }
      from '@/utils/system-dict-api'
  import { changeGradeTypeApi, getCourseTypeApi, changeSchoolTypeApi } from '@/utils/education-api'
  let thisPage = null
  export default {
    name: 'course',
    components: {courseQuestionDialogList},
    data () {
      let checkCourseName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入课程名称'))
        }
        callback()
      }
      return {
        questionListDialog: false,
        headers: {
          token: localStorage.getItem('token')
        },
        fileUrl: this.$http.getFileHost(),
        uploadAction: this.$http.httpUrl('/upload/2'),
        grade_type: '',
        currentPage: 1,
        pageSize: 10,
        totalCount: 0,
        parentCourseList: [],
        showFlag: false,
        courseTypeList: [],
        form: {
          head_img: '',
          status: 1, // 默认状态为草稿
          name: '',
          recommend_index_flag: 0,
          represent: '',
          grade_type: '',
          school_type: '',
          subject_id: '',
          code: '',
          sort: 0
        },
        loading: true,
        query: {
          keyWord: '',
          grade_type: '',
          school_type: ''
        },

        rules: {
          name: {
            required: true, validator: checkCourseName, trigger: 'blur'
          },
          school_type: {
            required: true, message: '请选择阶段', trigger: 'blur'
          },
          grade_type: {
            required: true, message: '请选择年级', trigger: 'blur'
          },
          subject_id: {
            required: true, message: '请选择科目', trigger: 'blur'
          },
          describe: {
            required: true, message: '请输入课程介绍', trigger: 'blur'
          }
        },
        queryParams: {
          mode_type: '',
          subject_id: '',
          school_type: '',
          grade_type: '',
          question_type: ''
        },
        headImageVisible: false,
        courseList: [],
        subjectList: [], // 科目列表
        schoolTypeList: [],
        gradeTypeList: [],
        gradeTypeListForQuery: [],
        changeGradeTypeList: [],
        changeSubjectList: []
      }
    },

    beforeCreate () {
      thisPage = this
    },

    watch: {
      'form.grade_type' (val) {
        this.form.grade_type = val
      },

      'form.subject_id' (val) {
        this.form.subject_id = val
      }
    },

    mounted () {
      let that = this
      this.getCourseList()
      this.getSubjectList()

      getGradeTypeListApi((data) => {
        that.gradeTypeList = data
        that.changeGradeTypeList = data
      })
      getSchoolTypeListApi((data) => {
        that.schoolTypeList = data
      })
    },

    methods: {

      // 上架或下架
      undercarriageCourse (item, status) {
        let message = null
        if (status === 1) {
           message = '确定下架课程' + item.name
        } else if (status === 2) {
           message = '确定上架课程' + item.name
        }
        this.$confirm(message + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.id = item.id
          this.form = {
            head_img: item.head_img,
            name: item.name,
            grade_type: item.grade_type,
            school_type: item.school_type,
            subject_id: item.subject_id,
            sort: item.sort,
            status: status,
            represent: item.represent,
            id: item.id,
            recommend_index_flag: item.recommend_index_flag ? 1 : 0
          }
          this.saveCommon(this)
        })
      },

      lookHeadImg () {
        this.headImageVisible = true
      },

      deleteHeadImg () {
        let that = this
        that.$confirm('确定移除学员头像吗？')
          .then(function () {
            that.form.head_img = ''
          })
          .catch(function (error) {
            console.log(error)
          })
      },

      updateCourse (item) {
        this.form = {
          head_img: item.head_img,
          name: item.name,
          grade_type: item.grade_type,
          school_type: item.school_type,
          subject_id: item.subject_id,
          sort: item.sort,
          status: item.status,
          represent: item.represent,
          id: item.id,
          recommend_index_flag: item.recommend_index_flag ? 1 : 0
        }
        this.showFlag = true
      },

      closeCourseQuestionDialog () {
        this.questionListDialog = false
      },

      relevanceCourseQuestion (item) {
        this.queryParams = {
          school_type: item.school_type,
          grade_type: item.grade_type,
          subject_id: item.subject_id,
          id: item.id
        }
        this.questionListDialog = true
      },

      getStringLength (str) {
        let len = 0
        for (let i = 0; i < str.length; i++) {
          let c = str.charCodeAt(i)
        // 单字节加1
          if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) {
            len++
          } else {
            len += 2
          }
        }
        return len
      },

      searchCourse () {
        this.currentPage = 1
        this.getCourseList()
      },

      beforeUploadHeadImg (file) {
        let imgContentType = ['application/x-png', 'application/png', 'image/png', 'image/jpeg', 'image/gif']
        if (imgContentType.indexOf(file.type) === -1) {
          this.$message.error('图片格式错误, 只能上传JPG/PNG 格式,请重新上传')
          return false
        }
        let isLimit = file.size / 1024 / 1024 < 5
        if (!isLimit) {
          this.$message.error('上传图片大小不能超过 5MB!')
          return false
        }
        return true
      },

      uploadHeadImgSuccess (res, file) {
        if (res.code === 1) {
          this.form.head_img = res.url
        } else {
          this.$message.error(res.message)
        }
      },

      saveCommon (that) {
        that.axios.post(that.$http.httpUrl('/system/course'), that.form)
          .then(function (response) {
            that.showFlag = false
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getCourseList()
              // that.getTreeCourse()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          }).catch(function (error) {
          console.log(error)
        })
      },


      saveOrUpdateCourse (status) {
        let that = this

        that.$refs['form'].validate(function (valid, rules) {
          if (valid) {
           // that.form.parent_id = parentId
            that.form.status = status
            that.saveCommon(that)
          } else {
            let message = ''
            for (let rule in rules) {
              message = rules[rule][0].message
              if (message) {
                break
              }
            }
            that.$message({
              type: 'error',
              message: message
            })
            return false
          }
        })
      },
      changeSchoolType (val) {
        let that = this
        if (that.form.grade_type) {
          that.form.grade_type = ''
        }
        let parentId = null
        that.schoolTypeList.forEach(item => {
          if (val === item.code) {
            parentId = item.id
          }
        })
        getDictValueListByParentId(parentId, 'grade_type', data => {
          that.changeGradeTypeList = data
        })
      },

      changeSchoolTypeForQuery (val) {
          let that = this
          let parentId = null
          that.schoolTypeList.forEach(item => {
              if (val === item.code) {
                  parentId = item.id
              }
          })
          getDictValueListByParentId(parentId, 'grade_type', data => {
              that.gradeTypeListForQuery = data
          })
      },

      changeGradeType (val) {
        let that = this
        if (that.form.subject_id) {
          that.form.subject_id = ''
        }
        changeGradeTypeApi(val, function (data) {
          that.changeSubjectList = data
        })
      },

      addCourse () {
        this.showFlag = true
        this.form = {
          status: 1,
          recommend_index_flag: 0,
          head_img: '',
          name: '',
          grade_type: '',
          represent: '',
          school_type: '',
          subject_id: '',
          code: '',
          sort: 0
        }
      },
      // 每页数
      sizeChangeHandler (val) {
        this.pageSize = val
        this.currentPage = 1
        this.getCourseList()
      },
      // 当前页
      currentChangeHandler (val) {
        this.currentPage = val
        this.getCourseList()
      },

      deleteCourseById (item) {
        let that = this
        that.$confirm('确定删除课程' + item.name + ',此操作将删除该课程及其关联数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/course'), {
            data: item
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getCourseList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      },

      getSchoolType () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/dict'), {
          params: {
            'type': 'school_type'
          }
        }).then(function (response) {
          that.schoolTypeList = response.data.data.dataList
        })
      },

      formatterCreateDate (row, column) {
        if (!row.create_date) {
          return '--'
        }
        return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
      },

      getGradeType () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/dict'), {
          params: {
            'type': 'grade_type'
          }
        }).then(function (response) {
          that.gradeTypeList = response.data.data.dataList
          that.changeGradeTypeList = response.data.data.dataList
        })
      },

      getCourseList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/course/list'), {
          params: {
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize,
            schoolType: that.query.school_type,
            gradeType: that.query.grade_type,
            keyWord: that.query.keyWord
          }
        }).then(function (response) {
          that.loading = false
          that.courseList = response.data.data.dataList
          that.totalCount = response.data.data.total
        })
      },

      getSubjectList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/subject/list'), {
          params: {
            sqlId: 'system.subject.list'
          }
        }).then(function (response) {
          that.subjectList = response.data.data.dataList
          that.changeSubjectList = response.data.data.dataList
        })
      }
    },

    filters: {
      getGradeName (gradeType) {
        for (let i in thisPage.gradeTypeList) {
          if (thisPage.gradeTypeList[i].code === gradeType) {
            return thisPage.gradeTypeList[i].value
          }
        }
      }
    }
  }
</script>
<style>
  .el-table__expand-icon {
    display: inline-block;
    margin-right: 15px;
    vertical-align:-5px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
